package com.xmg.p2p.base.service.impl;

import com.xmg.p2p.base.domain.VerifyCodeVO;
import com.xmg.p2p.base.service.IVerifyCodeService;
import com.xmg.p2p.base.util.BidConst;
import com.xmg.p2p.base.util.DateUtil;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Random;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Value("${sms.url}")
    private String url;
    @Value("${sms.username}")
    private String username;
    @Value("${sms.password}")
    private String password;
    @Value("${sms.apiKey}")
    private String apiKey;
    @Override
    public void sendVerifyCode(String phoneNumber) {
        VerifyCodeVO vc = UserContext.getVerifyCode();
        //判断当前能否发送短信，从session中获取最后发送时间
        if (vc == null || DateUtil.secondsBetween(new Date(), vc.getLastSendTime()) > 90) {

            String verifyCode = getCode();

            //发送短信
            try {
                URL url = new URL(this.url);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                StringBuilder content = new StringBuilder(100)
                        .append("username=").append(username)
                        .append("&password=").append(password)
                        .append("&apikey=").append(apiKey)
                        .append("&mobile=").append(phoneNumber)
                        .append("&content=").append("验证码是：").append(verifyCode).append(",请在5分钟内使用");
                //设置请求方法，get post 必须要大写
                conn.setRequestMethod("POST");
                //设置POST请求是有请求体的
                conn.setDoOutput(true);
                //写入请求体
                conn.getOutputStream().write(content.toString().getBytes());
                //得到响应流（其实就已经发送了）
                String response = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("UTF-8"));
                if(response.startsWith("success:")){
                    vc = new VerifyCodeVO();
                    vc.setPhoneNumber(phoneNumber);
                    vc.setVerifyCode(verifyCode);
                    vc.setLastSendTime(new Date());
                    UserContext.putVerifyCode(vc);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("短信发送失败!");
            }
        } else {
            throw new RuntimeException("发送过于频繁");
        }

    }

    @Override
    public boolean verify(String phoneNumber, String verifyCode) {
        VerifyCodeVO vc = UserContext.getVerifyCode();
        if (vc != null && vc.getPhoneNumber().equals(phoneNumber)
                && vc.getVerifyCode().equals(verifyCode)
                && DateUtil.secondsBetween(vc.getLastSendTime(), new Date()) < BidConst.VERIFYCODE_VAILDATE_SECOND){
            return true;
        }
        return false;
    }

    public static String getCode() {
        Random r = new Random();
        return r.nextInt(1000000) + "";
    }
}
